OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
    defaultHandlerOptions: {
        'single': true,
        'double': false,
        'pixelTolerance': 0,
        'stopSingle': false,
        'stopDouble': false,
        'map' : ''
    },
    initialize: function(options) {
        this.handlerOptions = OpenLayers.Util.extend(
            {}, this.defaultHandlerOptions
        );
        OpenLayers.Control.prototype.initialize.apply(
            this, arguments
        );
        this.handler = new OpenLayers.Handler.Click(
            this, {
                'click': this.trigger
            }, this.handlerOptions
        );
        $('available_layers').observe('change', function(){$('map_props').submit()});
    },
    trigger: function(e) {
        var lonlat = this.map.getLonLatFromViewPortPx(e.xy);
        element = $('ajax_url');
        var params = 'x=' + lonlat.lon + '&y='+ lonlat.lat+'&';
        $$('#map_props select').each(function(element){
            params +=  element.readAttribute('name') + '=' + element.value + '&';
        }.bind(params));
        $$('#map_props input').each(function(element){
           if(element.readAttribute('type') == 'checkbox')
            {
                if(element.checked)
                    params +=  element.readAttribute('name') + '=' + element.value.gsub("#", "") + '&';
            }
            else
                params +=  element.readAttribute('name') + '=' + element.value.gsub("#", "") + '&';
        }.bind(params));
        new Ajax.Request(element.href, {
            method: "post",
            parameters : params,
            onSuccess: this.showResults.bind(this),
            onLoading : function(){$('overall').addClassName('loading-image'); $('map').addClassName('loading-image');}
        });
    },
    showResults: function(response)
    {
        $('overall').removeClassName('loading-image');
        $('map').removeClassName('loading-image');
        arr_response = response.responseJSON;
        if(arr_response !== null)
        {
            $('result_region').update(arr_response['meta']['language_result']+' '+ arr_response['meta']['region']);
            if(arr_response['meta'].results > 0)
            {
                insert_string = '<ol>';
                for(cnt=0; cnt<arr_response['meta'].results; ++cnt)
                    insert_string += '<li><a href="index.php?input=map&m_id='+arr_response['data'][cnt].dt_id+'" title="'+arr_response['data'][cnt].e_name+'">' +arr_response['data'][cnt].dt_titel+'</a>';
                insert_string += '</ol>';
            }
            else
               insert_string = '<p>' + arr_response['meta']['nodata'] + '</p>';
        }
        else
             insert_string = 'Sorry, an error occurred';
        $('available_maps').update(insert_string).addClassName('available_maps_update');
        window.setTimeout(function(){$('available_maps').removeClassName('available_maps_update');}, 2000);
    }
});
var Configurable = {
    setOptions: function(options) {
        this.options = {};
        var constructor = this.constructor;
        if (constructor.superclass) {
            var chain = [], klass = constructor;
            while (klass = klass.superclass) chain.push(klass);
            chain = chain.reverse();
            for (var i = 0, len = chain.length; i < len; ++i)
            {
                if(klass !== null)
                    Object.extend(this.options, klass.DEFAULT_OPTIONS || {});
            }
        }
        Object.extend(this.options, constructor.DEFAULT_OPTIONS);
        return Object.extend(this.options, options || {});
    }
};
Policies_Analysis_Window = Class.create(Configurable, {
    body_node_ : "",
    elemet_url_ : "",
    pol_overlay_ : null,
    initialize: function(options)
    {
        this.setOptions(options);
        $$('body').each(function(body){
            this.body_node_ = body;
        }.bind(this));
        $(this.options.analysis_id).observe('click', this.showWindow.bindAsEventListener(this));
    },
    showWindow : function(event)
    {
        var element = Event.findElement(event, 'a.'+this.options.clickable_class);
        if(element == null || element == document)
            return false;
        event.stop();
        this.createWindow();
        if(this.pol_overlay_ == null)
            this.pol_overlay_ = new Policies_Overlay_Link_Focus(element, 'analysis-window-close', 'analysis-window-focus', this);
        this.element_url_ = element.href;
        new Ajax.Request(element.href, {
            method: "get",
            parameters : {'amode':'ajax'},
            onSuccess: this.updateInformation.bind(this),
            onFailure: function(){window.location.href = element.href}.bind(element)
        });
    },
    updateInformation : function(response)
    {
        try{
            $('analysis-window').setStyle({'textAlign':'left'}).update(response.responseText);
            response.responseText.eval_js();
        }
        catch(err)
        {
            window.location.href = this.element_url_;
        }
    },
    createWindow : function()
    {
        if($('analysis-window-container')==null)
        {
            var width, height, left, top, font_size;
            font_size = 16;
            width = Math.floor(this.body_node_.getStyle('width').sub('px', '')*9/10);
            height = Math.floor(document.viewport.getHeight()*9/10);
            left = Math.floor((this.body_node_.getStyle('width').sub('px', '')-width-font_size)/2) + 'px';
            top = Math.floor((document.viewport.getHeight()-height-font_size)/2) + 'px';
            width += 'px';
            height += 'px';
            this.body_node_.insert('<div id="analysis-window-container" aria-hidden="true"></div>');
            $('analysis-window-container').setStyle({'left': left, 'top' : top, 'width' : width, 'height' : height}).insert('<a id="analysis-window-focus" name="analysis-window-focus" tabindex="-1"></a><a href="#" id="analysis-window-close" role="button" aria-controls="analysis-window-container">Close</a><div id="analysis-window"></div>');
            $('analysis-window-close').observe('click', this.closeWindow.bindAsEventListener(this));
        }
        this.body_node_.addClassName('analysis-window-js-overlay');
        $('analysis-window').setStyle({'textAlign':'center'}).update('<img src="output/images/ajax-loader_big.gif" alt="Loading..." class="loadingimage" />');
        $('analysis-window-container').show().writeAttribute({'aria-hidden': 'false'});
    },
    closeWindow : function(event)
    {
        $('analysis-window-container').hide().writeAttribute({'aria-hidden': 'true'});
        this.body_node_.removeClassName('analysis-window-js-overlay');
        this.pol_overlay_.closeOverlay();
        this.pol_overlay_ = null;
        event.stop();
    }
});

Policies_Analysis_Window.DEFAULT_OPTIONS = {
    analysis_id: 'analysis',
    clickable_class: 'analysiswindow'
};
Policies_Overlay_Link_Focus = Class.create({
    bound_handler_method_ : '',
    event_node_ : '',
    close_link_id_ : '',
    overlay_focus_id_: '',
    calling_class_ : '',
    initialize: function(element, close_link_id, overlay_focus_id, calling_class)
    {
        this.event_node_ = element;
        this.close_link_id_ = close_link_id;
        this.overlay_focus_id_ = overlay_focus_id.toString();
        this.calling_class_ = calling_class;
        this.bound_handler_method_ = this.keyboardInput.bind(this);
        this.makeLinksInactive();
        document.observe('keydown', this.bound_handler_method_);
        $(this.overlay_focus_id_).focus();
    },
    keyboardInput: function(event)
    {
        var keycode = event.keyCode;
        var escape_key;
        if (event.DOM_VK_ESCAPE) {
            escape_key = event.DOM_VK_ESCAPE;
        } else { // ie
            escape_key = 27;
        }
        if(event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40)
            event.stop();
        if(keycode == escape_key)
            this.calling_class_.closeWindow(event);
    },
    makeLinksInactive : function()
    {
        $$('a').each(function(link){
            if(link.readAttribute('tabindex') == null && (link.readAttribute('id') == null || (link.readAttribute('id') != this.close_link_id_ && link.readAttribute('id') != this.overlay_focus_id_)))
            {
                link.writeAttribute({'tabindex': '-1'});
                link.addClassName('pol-overlay-inactive');
            }
        }.bind(this));
        $$('input').each(function(input){
            input.writeAttribute({'tabindex': '-1'});
            input.addClassName('pol-overlay-inactive');
        });
        $$('select').each(function(input){
            input.writeAttribute({'tabindex': '-1'});
            input.addClassName('pol-overlay-inactive');
        });
    },
    makeLinksActive : function()
    {
        $$('.pol-overlay-inactive').each(function(element){
            element.writeAttribute({'tabindex': null});
            element.removeClassName('lightbox-inactive');
        });
    },
    closeOverlay : function()
    {
        this.makeLinksActive();
        this.event_node_.focus();
        document.stopObserving('keydown', this.bound_handler_method_);
    }
});
Policies_Ui = Class.create({
    form_id_ : "search_form",
    form_container_ : "searchform_container",
    input_placeholder_ : "Titel durchsuchen",
    arr_cell_classes_ : new Array,
    arr_search_values_ : new Array,
    checksum_ : 0,
    cell_cnt_ : 0,
    hash_ : '',
    tmp_hash_ : '',
    reset_lock_ : false,
    initialize: function(class_name)
    {
        if ($(this.form_id_)!=null)
        {
            if("onhashchange" in window || Prototype.Browser.Opera)
            {
                window.onhashchange = this.checkHash.bind(this);
                this.prepareTable();
                this.initSearchBox();
                if(window.location.hash.length > 0 && window.location.hash != 'none')
                    this.checkHash();
                this.hash_ = window.location.hash;
            }
            else
                return false;
        }
        else
            return false;
    },
    checkHash : function()
    {
        if(this.hash_ != window.location.hash)
        {
            var arr_tmp, arr_param;
            arr_tmp = window.location.hash.substr(1, window.location.hash.length).split("&");
            this.reset_lock_ = true;
            $(this.form_id_).reset();
            this.reset_lock_ = false;
            for(cnt=0; cnt < arr_tmp.length; ++cnt)
            {
                arr_param = arr_tmp[cnt].split("=");
                if(arr_param.length == 2)
                    $(arr_param[0]).value=arr_param[1];
            }
            this.updateTable();
        }
    },
    prepareTable: function()
    {
        $$('#datatable tr').each(function(row){
            var arr_header_cells = row.getElementsByTagName('th');
            for(cnt=0; cnt<arr_header_cells.length; ++cnt)
                this.arr_cell_classes_[cnt] = arr_header_cells[cnt].className;
            this.cell_cnt_ = 0;
            $$('#datatable td').each(function(cell){
                var length = this.arr_cell_classes_.length;
                cell.addClassName(this.arr_cell_classes_[this.cell_cnt_++ % length]);
            }.bind(this));
        }.bind(this));
    },
    initSearchBox: function()
    {
        var searchfield = $('t_title');
        if((searchfield.placeholder === undefined && searchfield.placeHolder === undefined) || Prototype.Browser.IE)
            searchfield.value=this.input_placeholder_;
        searchfield.observe('click', function(event){event.findElement().value='';});
        $(this.form_id_).observe('submit', this.stopFormEvent.bindAsEventListener(this));
        $(this.form_id_).observe('reset', this.resetTable.bindAsEventListener(this));
        $(this.form_container_).setStyle({'display' : 'block'});
    },
    stopFormEvent : function(event)
    {
        event.preventDefault();
        this.updateTable();
    },
    updateTable : function()
    {
        this.tmp_hash_ = '';
        $$('#'+this.form_id_+' input[type=text]').each(function(element){
            this.addDataToSearchArray(element.value, element.id);
        }.bind(this));
        $$('#'+this.form_id_+' select').each(function(element){
            this.addDataToSearchArray(element.value, element.id);
        }.bind(this));
        window.location.hash = this.tmp_hash_;
        this.hash_ = window.location.hash;
        $$('#datatable tr').each(function(row){
            var arr_cells = row.getElementsByTagName('td');
            var tmp_checksum = 0;
            for(cnt=0; cnt<arr_cells.length; ++cnt)
            {
                var class_name = arr_cells[cnt].className;
                for(sub_cnt=0; sub_cnt<this.arr_search_values_.length;++sub_cnt)
                {
                    if(this.arr_search_values_[sub_cnt].getName() == class_name)
                    {
                        var re = new RegExp(this.arr_search_values_[sub_cnt].getValue(),"i");
                        if(!this.arr_search_values_[sub_cnt].isNegation() && arr_cells[cnt].innerHTML.search(re) != -1)
                            ++tmp_checksum;
                        if(this.arr_search_values_[sub_cnt].isNegation() && arr_cells[cnt].innerHTML.search(re) == -1)
                            ++tmp_checksum;
                    }
                }
            }
            if(tmp_checksum>=this.checksum_ || arr_cells.length==0)
                row.show();
            else
                row.hide();
        }.bind(this));
        this.arr_search_values_ = new Array();
        this.checksum_ = 0;
    },
    resetTable : function(event)
    {
        var searchfield = $('t_title');
        if((searchfield.placeholder === undefined && searchfield.placeHolder === undefined) || Prototype.Browser.IE)
            searchfield.value=this.input_placeholder_;
        $$('#datatable tr').each(function(row){
            row.show();
        });
        if(!this.reset_lock_)
        {
            window.location.hash = 'none';
            this.hash_ = window.location.hash;
            this.tmp_hash_ = '';
        }
    },
    addDataToSearchArray : function(search_value, class_name)
    {
        if(!search_value.empty() && search_value != 0 && search_value.indexOf(this.input_placeholder_) == -1)
        {
            if(!this.tmp_hash_.empty())
                this.tmp_hash_ += '&';
            this.tmp_hash_ += class_name+'='+search_value;
            this.arr_search_values_.push(new Policies_Ui_Search_Value(search_value, class_name));
            ++this.checksum_;
        }
    }
});
Policies_Ui_ClassLimits = Class.create({
    event_node_ : '',
    row_cnt_ : 0,
    arr_response_ : '',
    initialize: function()
    {
        if($('classwidth')===null)
            return false;
        $('classwidth').observe('change', this.changeClassLimits.bindAsEventListener(this));
        $('classification').observe('click', this.toggleOptions.bindAsEventListener(this));
    },
    changeClassLimits: function()
    {
        if($('user_classes').checked)
        {
            element = $('reset_class_limits');
            new Ajax.Request(element.href, {
                method: "get",
                parameters : { 'mode' : 'ajax', 'classwidth' : $F('classwidth')},
                onSuccess: this.updateClasses.bind(this),
                onLoading : $('classwidth').writeAttribute('disabled', 'disabled')
            });
        }
    },
    updateClasses : function(response)
    {
        var class_length, tmp_div, insert_string;
        this.arr_response_ = response.responseJSON;
        class_length = parseInt($F('classwidth'));
        if((class_length+1) == this.arr_response_.length)
        {
            $$('#equal_classes_option_values input').each(function(element){
                element.remove();
            });
            $$('#equal_classes_option_values span').each(function(element){
                element.remove();
            });
            insert_string = '';
            for(cnt=0; cnt<this.arr_response_.length; ++cnt)
            {
                insert_string += '<input type="text" name="arr_classlimits[]" value="' +this.arr_response_[cnt]+'" />';
                if(cnt < class_length)
                    insert_string += '<span>&lt;</span>';
            }
            $('equal_classes_option_values').insert({ 'top' : insert_string});
        }
        else
            alert('Es gab leider Probleme');
        $('classwidth').writeAttribute('disabled', false);
    },
    toggleOptions : function(event)
    {
        element = event.findElement('input');
        if(element != null && element.hasAttribute('id') && element.readAttribute('id') != 'classwidth')
        {
            if(element.readAttribute('id') == 'user_classes')
            {
                this.changeClassLimits();
                $('equal_classes_options').show();
            }
            else
                $('equal_classes_options').hide();
        }
        element = event.findElement('a');
        if(element != null && element.hasAttribute('id') && element.readAttribute('id') == 'reset_class_limits')
        {
            event.stop();
            this.getDefaultValues(element);
        }
    },
    getDefaultValues : function(element)
    {
        this.event_node_ = element.href;
        new Ajax.Request(element.href, {
            method: "get",
            parameters : { 'mode' : 'ajax'},
            onSuccess: this.updateDefaultValues.bind(this),
            onFailure : function(){window.location.href = this.event_node_}.bind(this)
        });
    },
    updateDefaultValues : function(response)
    {
        this.arr_response_ = response.responseJSON;
        $$('#equal_classes_option_values input').each(function(element){
            if(this.row_cnt_ < this.arr_response_.length)
                element.value = this.arr_response_[this.row_cnt_];
            ++this.row_cnt_
        }.bind(this));
        this.row_cnt_ = 0;
    }
});
Policies_Ui_Map = Class.create({
    map_ : "",
    wms_url_ : "",
    wms_layer_ : false,
    layer_cnt_ : 0,
    legend_url_ : "",
    is_disabled_ : false,
    timeout_id_ : 0,
    initialize: function(wms_url, projection, arr_bbox, max_resolution, clickable, legend_url)
    {
        var options = {
            projection: new OpenLayers.Projection("EPSG:"+projection),
            displayProjection: new OpenLayers.Projection("EPSG:"+projection),
            maxResolution: max_resolution,
            maxExtent: new OpenLayers.Bounds(arr_bbox[0], arr_bbox[1], arr_bbox[2], arr_bbox[3]),
            controls: [
                        new OpenLayers.Control.Navigation(),
                        new OpenLayers.Control.PanZoom(),
                        new OpenLayers.Control.OverviewMap()
                    ]
        };
        this.wms_url_ = wms_url;
        if ($('no_js_map')!=null)
            $('no_js_map').hide();
        this.resizeWindow();
        $('map').removeClassName('skip');
        this.map_ = new OpenLayers.Map('map', options);
        this.addLayer();
        if(clickable)
        {
            var click = new OpenLayers.Control.Click(this.map_);
            this.map_.addControl(click);
            click.activate();
        }
        else
        {
            this.legend_url_ = legend_url;
            $('map').insert({'bottom': '<div id="legend"><img src="' + this.legend_url_ +'&d='+ ++this.layer_cnt_  +'&SERVICE=WMS&VERSION=1.1.1&layer=data_layer&REQUEST=getlegendgraphic&FORMAT=image/png" class="ol_legend" /></div>'});
            $('map_props').observe('submit', this.updateParams.bindAsEventListener(this));
            if($('slideshow') != null)
                $('slideshow').observe('change', this.slideshow.bindAsEventListener(this));
            if(Prototype.Browser.IE && (parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6 || parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7))
                return false;
            new Policies_Analysis_Window();
        }
    },
    slideshow : function(event)
    {
        if($('slideshow').checked)
        {
            $$('select.data_columns').each(function(element){
                if(element.value == -1)
                    element.addClassName('slideshow-run');
            })
            this.runSlideshow();
        }
        else
        {
            window.clearTimeout(this.timeout_id_);
            $$('select.slideshow-run').each(function(element){
                element.removeClassName('slideshow-run');
                arr_elements = $(element.id);
                for(cnt=0; cnt < arr_elements.length; ++cnt)
                    arr_elements[cnt].writeAttribute('selected', false);
                arr_elements[0].writeAttribute('selected', 'selected');
            })
        }
    },
    runSlideshow : function()
    {
        $$('select.slideshow-run').each(function(element){
            arr_elements = $(element.id);
            for(cnt=0; cnt < arr_elements.length; ++cnt)
            {
                if(element.value == arr_elements[cnt].value)
                {
                    arr_elements[cnt].writeAttribute('selected', false);
                    if(cnt+1 == arr_elements.length)
                    {
                        arr_elements[1].writeAttribute('selected', 'selected');
                    }
                    else
                    {
                        arr_elements[cnt+1].writeAttribute('selected', 'selected');
                    }
                    break;
                }
            }
        })
        this.updateParams();
        this.timeout_id_ = window.setTimeout(this.runSlideshow.bind(this), 5000);
    },
    updateParams : function(event)
    {
        var params = '';
        $$('#map_props select').each(function(element){
            params +=  element.readAttribute('name') + '=' + element.value + '&';
        }.bind(params));
        $$('#map_props input').each(function(element){
            if(element.readAttribute('type') == 'radio' || element.readAttribute('type') == 'checkbox')
            {
                if(element.checked)
                    params +=  element.readAttribute('name') + '=' + element.value.gsub("#", "") + '&';
            }
            else
                params +=  element.readAttribute('name') + '=' + element.value.gsub("#", "") + '&';
        }.bind(params));
        if(event != undefined)
            event.stop();
        if(!this.is_disabled_)
        {
            new Ajax.Request($('map_props').action, {
                method: "post",
                parameters : params,
                onSuccess: this.setFocusToMap.bind(this),
                onFailure: function(){$('map_props').submit();},
                onLoading: this.updateSubmitButton.bind(this)
            });
        }
    },
    updateSubmitButton : function()
    {
        $('refreshmap').writeAttribute('disabled', 'disabled');
        this.is_disabled_ = true;
    },
    setFocusToMap : function()
    {
        window.location.href = '#map';
        this.updateLegend();
    },
    updateLegend : function()
    {
        this.addLayer();
        var img_preloader = new Image();
        img_preloader.onload = function(){
            $('legend').update('<img src="'+img_preloader.src+'" class="ol_legend" />');
            $('legend').setStyle({'height': img_preloader.height + 'px', 'width': img_preloader.width + 'px'});
        }.bind(this);
        img_preloader.src = this.legend_url_ +'&d='+ ++this.layer_cnt_ +'&SERVICE=WMS&VERSION=1.1.1&layer=data_layer&REQUEST=getlegendgraphic&FORMAT=image/png';
    },
    addLayer : function()
    {
        if(this.wms_layer_ !== false)
        {
            var bounds = this.wms_layer_.getExtent();
            this.map_.removeLayer(this.wms_layer_);
            this.wms_layer_.destroy();
        }
        this.wms_layer_ = new OpenLayers.Layer.WMS( "OpenLayers WMS" + ++this.layer_cnt_, this.wms_url_+'&d='+this.layer_cnt_, {layers: 'BEZ'}, {singleTile: true});
        this.map_.addLayer(this.wms_layer_);
        if(!this.is_disabled_)
            this.map_.zoomToMaxExtent();
        else
            this.map_.zoomToExtent(bounds);
        if(this.is_disabled_)
            $('refreshmap').writeAttribute('disabled', false);
        this.is_disabled_=false;
    },
    resizeWindow : function()
    {
        $('content').removeClassName('content');
        var height = document.viewport.getHeight()-$('content').cumulativeOffset().top;
        $('content').setStyle({'height': height + 'px'});
        $('optionsidebar').setStyle({'height': height + 'px', 'overflow': 'auto', 'margin-bottom' : 0});
        $('map').setStyle({'height': height + 'px'});
    }
});
Policies_Ui_Search_Value = Class.create({
    class_name_ : "",
    search_value_ : "",
    is_negation_ : false,
    initialize: function(search_value, class_name)
    {
        this.class_name_ = class_name;
        if(search_value.charAt(0) == '!')
        {
            this.search_value_ = search_value.slice(1);
            this.is_negation_ = true;
        }
        else
            this.search_value_ = search_value;
    },
    getName : function()
    {
        return this.class_name_;
    },
    getValue : function ()
    {
        return this.search_value_;
    },
    isNegation : function()
    {
        return this.is_negation_;
    }
});
Selectbox = Class.create(Configurable, {
    body_node_ : '',
    initialize: function(options)
    {
        this.setOptions(options);
        this.run();
    },
    run : function()
    {
        $$('body').each(function(body){
            body.writeAttribute({'role': 'application'});
            this.body_node_ = body;
        }.bind(this));
        $$('select.' + this.options.class_name).each(function(element){
            this.createSelectList(element);
            this.createMenuLink(element);
            element.hide().writeAttribute({'aria-hidden': 'true'});
            var id = element.readAttribute('id') + '-' + this.options.link_name;
            $$('label[for="'+element.readAttribute('id')+'"]').each(function(label){
                label.writeAttribute({'for': id});
            }.bind(id));
        }.bind(this));
        this.body_node_.observe('click', this.checkList.bindAsEventListener(this));
    },
    createSelectList : function(element)
    {
        var offset = element.cumulativeOffset();
        var list = '<ul id="' + element.readAttribute('id') + '-' + this.options.link_name + '-menu" aria-labelledby="' + element.readAttribute('id') + '-' + this.options.link_name + '" aria-hidden="true" role="listbox" class="selectbox-menu" style="display: none; left: '+offset.left+ 'px; top:'+ (offset.top+element.getHeight())+ 'px;">';
        element.childElements().each(function(listitem){
            list += '<li';
            if(listitem.selected)
                list +=' aria-selected="true"';
            list += '><a href="#" role="option">'+listitem.innerHTML+'</a><span class="option-value skip">'+listitem.readAttribute('value')+'</span></li>';
        }.bind(list));
        this.body_node_.insert({'bottom' : list});
        if($(element.readAttribute('id') + '-' + this.options.link_name + '-menu').select('[aria-selected="true"]').length == 0)
            $(element.readAttribute('id') + '-' + this.options.link_name + '-menu').firstDescendant().writeAttribute({'aria-selected' : 'true'});
    },
    createMenuLink : function(element)
    {
        var s_option;
        $(element.readAttribute('id') + '-' + this.options.link_name + '-menu').select('[aria-selected="true"]').each(function(option){
            s_option = option;
        }.bind(s_option));
        var link = '<a id="' + element.readAttribute('id') + '-' + this.options.link_name + '" href="#" class="custom-select group" aria-haspopup="true" role="button" aria-owns="'+element.readAttribute('id') + '-' + this.options.link_name + '-menu"><span class="custom-select-text">'+s_option.firstDescendant().innerHTML+'</span><span class="custom-select-button-icon"></span>';
        element.insert({after: link});
    },
    checkList : function(event)
    {
        if(!this.catchButtonEvent(event) && !this.updateMenu(event))
            this.hideOpenMenus(event);
    },
    catchButtonEvent : function(event)
    {
        var menu, element;
        element = event.findElement('a.custom-select');
        if(element == null || element == document)
            return false;
        event.stop();
        menu = $(element.readAttribute('id')+'-menu');
        this.toggleMenu(menu);
        return true;
    },
    toggleMenu : function(menu)
    {
        if(menu.getStyle('display') == 'none')
        {
            menu.show();
            menu.writeAttribute({'aria-hidden' : 'false'});
            var element = $(menu.readAttribute('aria-labelledby'));
            var offset = element.cumulativeOffset();
            menu.setStyle({left: offset.left+'px', top: (offset.top+element.getHeight())+'px'});
        }
        else
        {
            menu.hide();
            menu.writeAttribute({'aria-hidden': 'true'});
        }
    },
    updateMenu : function(event)
    {
        var element = event.findElement('ul.selectbox-menu li a');
        if(element == null || element == document)
            return false;
        event.stop();
        var menu = element.up().up();
        if(menu.readAttribute('id') == null)
            return false;
        $$('a[aria-owns="'+menu.readAttribute('id')+'"]').each(function(link){
            link.firstDescendant().innerHTML = element.innerHTML;
        }.bind(element));
        $$('#'+menu.readAttribute('id')+' li[aria-selected="true"]').each(function(link){
            link.writeAttribute({'aria-selected' : 'false'});
        });
        element.up().writeAttribute({'aria-selected' : 'true'});
        var id = element.up().up().readAttribute('id').gsub('-' + this.options.link_name + '-menu', '');
        var option_value = element.up().select('.option-value').first().innerHTML;
        $(id).select('option[selected]').first().selected = false;
        $(id).select('option[value="'+option_value+'"]').first().selected=true;
        this.toggleMenu(menu);
        return element.next().innerHTML;
    },
    hideOpenMenus : function(event)
    {
        $$('ul[aria-hidden="false"]').each(function(menu){
            this.toggleMenu(menu);
        }.bind(this));
    }
});

Selectbox.DEFAULT_OPTIONS = {
    class_name: 'selectbox',
    link_name: 'button'
};
Spindown = Class.create(Configurable, {
    body_node_ : '',
    initialize: function(options)
    {
        this.setOptions(options);
        this.run();
    },
    run : function()
    {
        $$('body').each(function(body){
            body.writeAttribute({'role': 'application'});
            this.body_node_ = body;
        }.bind(this));
        $$('.' + this.options.class_name + ' ' + this.options.clickable_element).each(function(element){
            element.addClassName(this.options.clickable_element_class);
            element.update('<a href="#">'+element.innerHTML+'</a>');
            element.next().hide();
        }.bind(this));
        this.body_node_.observe('click', this.checkForSpindown.bindAsEventListener(this));
    },
    checkForSpindown : function(event)
    {
        var element;
        element = event.findElement('.' + this.options.class_name + ' ' + this.options.clickable_element + ' a');
        if(element == null || element == document)
            return false;
        event.stop();
        element.up().next().toggle();
    }
});

Spindown.DEFAULT_OPTIONS = {
    class_name: 'spindown',
    clickable_element: 'h3',
    clickable_element_class: 'spindown'
};
Tooltip = Class.create(Configurable, {
    body_node_ : '',
    arr_tooltip_links_ : '',
    link_cnt_ : 0,
    initialize: function(options)
    {
        this.setOptions(options);
        $$('body').each(function(body){
            body.writeAttribute({'role': 'application'});
            this.body_node_ = body;
        }.bind(this));
        this.arr_tooltip_links_ = $$('.'+this.options.class_name+'[title]');
        this.arr_tooltip_links_.each(function(link){
            this.body_node_.insert('<div id="tooltip-id-' + ++this.link_cnt_ + '" class="tooltip-detail" aria-hidden="true" role="tooltip" style="display: none;">' + link.readAttribute('title') + '</div>');
            link.writeAttribute({'title' : '', 'aria-describedby' : 'tooltip-id-' + this.link_cnt_});
        }.bind(this));
        if(this.arr_tooltip_links_.length > 0)
        {
            this.body_node_.observe('mouseover', this.showTooltip.bindAsEventListener(this));
            this.body_node_.observe('mouseout', this.hideTooltip.bindAsEventListener(this));
        }
    },
    showTooltip : function(event)
    {
        var element = event.findElement(this.options.tooltip_element);
        if(element == null || element == document)
            return false;
        if(!element.hasAttribute('aria-describedby'))
            return false;
        var div = $(element.readAttribute('aria-describedby'));
        div.setStyle({'left' : (event.pointerX()+20) + 'px', 'top' : (event.pointerY()+15) + 'px'}).writeAttribute({'aria-hidden': 'false'}).show();
    },
    hideTooltip : function(event)
    {
        var link = event.findElement(this.options.tooltip_element);
        if(link == null || link == document)
            return false;
        if(!link.hasAttribute('aria-describedby'))
            return false;
        $(link.readAttribute('aria-describedby')).writeAttribute({'aria-hidden': 'true'}).hide();
    }
});


Tooltip.DEFAULT_OPTIONS = {
    class_name: 'tooltip',
    tooltip_element: 'a'
};
document.observe('dom:loaded', function(){ new Tooltip({tooltip_element : 'label'}); new Policies_Ui_ClassLimits();});

/*
* inspired by te following two sources
* http://www.tutorials.de/javascript-ajax/272558-ajax-liefert-html-und-javascript-zurueck-und-das-js-soll-sofort-ausgefuehrt-werden.html#post1410695
* http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
*/
String.prototype.eval_js=function()
{
    d=document.createElement('div');
    d.innerHTML=this;
    c='';
    for(s=0;s<d.getElementsByTagName('script').length;++s)
    {
        if(d.getElementsByTagName('script')[s].innerHTML.length == 0)
        {
            fileref=document.createElement('script');
            fileref.setAttribute("type","text/javascript");
            fileref.setAttribute("src", d.getElementsByTagName('script')[s].src);
            document.getElementsByTagName("head")[0].appendChild(fileref);
        }
        else
            c+=d.getElementsByTagName('script')[s].innerHTML;
    }
    eval(c);
    delete d;
}

function elementsSupportsAttribute(element, attribute)
{
    var test = document.createElement(element);
    if(attribute in test)
        return true;
    else
        return false;
}

GIS_Selectbox = Class.create(Selectbox, {
    policies_ : '',
    initialize: function(options)
    {
        this.setOptions(options);
        $$('#choose-project-form input[type="submit"]').each(function(input){
            input.hide();
        });
        this.policies_ = new Policies_Ui();
        this.run();
    },
    checkList : function(event)
    {
        var topic_id = this.updateMenu(event);
        if(!this.catchButtonEvent(event) && topic_id === false)
            this.hideOpenMenus(event);
        if(topic_id !== false)
            this.updateDatatable(topic_id);

    },
    updateDatatable : function(t_id)
    {
        $('choose-project-form').submit();
    }
});

GIS_Selectbox.DEFAULT_OPTIONS = {
    class_name: 'selectbox',
    link_name: 'button',
    img_src : 'output/images/ajax-loader_big.gif'
};
